package org.example.ch12;

import java.util.Arrays;

/**
 * 打家劫舍
 */
public class Rob {

    public static void main(String[] args) {
        int[] nums = new int[]{1,2,3,1};
        int result = solution1(nums);
        System.out.println(result);

//        int[][] test = {{0, 1, 2}, {2, 1}, {1}};
//        for (int i=0;i<3;i++) {
//            System.out.println ( Arrays.toString (test[i]));
//        }
    }

    /**
     * 0=偷  1=不偷
     * @param nums  1,2,3,1
     * @return
     */
    public static int solution1(int[] nums){
        if(nums==null || nums.length==0){
            return 0;
        }
        int len = nums.length;
        if(len==1){
            return nums[0];
        }
        int[][] a = new int[len][2];
        //没偷的第一个元素
        a[0][0] = 0;
        a[0][1] = nums[1];
        for (int i = 1; i < nums.length; i++) {
            a[i][0] = Math.max(a[i-1][0],a[i-1][1]);
            a[i][1] = a[i-1][0]+nums[i];
        }

        return Math.max(a[len-1][0],a[len-1][1]);

    }

    /**
     * 动态规划的解决方案
     * @param nums
     * @return
     */
    public static int solution2(int[] nums){
        if(nums==null || nums.length==0){
            return 0;
        }
        int[] dp = new int[nums.length];

        if(nums.length>1){
            dp[0] = nums[0];
            dp[1] = Math.max(nums[0],nums[1]);
        }


        for (int i = 2; i < nums.length ; i++) {
            dp[i] = Math.max(dp[i-2]+nums[i],dp[i-1]);
        }
        return dp[nums.length-1];
    }

    /**
     * 动态规划+滚动数组
     * @param nums
     * @return
     */
    public static int solution3(int[] nums){
       if(nums==null || nums.length==0){
           return 0;
       }
       if(nums.length==1){
           return nums[0];
       }
       
       int pre = nums[0];
       int cur = Math.max(nums[0],nums[1]);
        for (int i = 2; i < nums.length; i++) {
          int temp = cur;
          cur = Math.max(pre+nums[i],cur);
          pre = temp;
        }
        return cur;
       
    }
}
